<?php
/**
 * @see Alinks_ImportExport_Import_Abstract
 */
require_once('Alinks/ImportExport/Import/Abstract.php');

/**
 * Utility class for importing keyphrases from XML
 *
 * Copyright (C) 2008  Sean Hickey
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Sean Hickey <sean@headzoo.com>
 * @version $Id: Xml.php 391 2008-07-03 05:42:56Z sean $
 * @package Alinks_ImportExport
 */
class Alinks_ImportExport_Import_Xml extends Alinks_ImportExport_Import_Abstract
{
	/**
	 * Imports an exported XML file
	 *
	 * @param string $xml The XML
	 * @return bool
	 * @throws Alinks_ImportExport_Import_Exception
	 */
	public function import($xml)
	{
		$xml = simplexml_load_string($xml);
		if (false === $xml) {
			/**
			 * @see Alinks_ImportExport_Import_Exception
			 */
			require_once('Alinks/ImportExport/Import/Exception.php');
			throw new Alinks_ImportExport_Import_Exception('The XML appears to be corrupt.');
		}
		
		$keyphrases = array();
		$factory_settings = array();
		$alinks_settings = array();
		
		if (isset($xml->Keyphrases->Keyphrase)) {
			foreach($xml->Keyphrases->Keyphrase as $keyphrase) {
				$k = new Alinks_Keyphrase((string)$keyphrase['factory']);
				$k->setPhrase((string)$keyphrase['phrase']);
				$k->setDescription((string)$keyphrase['description']);
				$k->setHash((string)$keyphrase['hash']);
				$k->setCreated((string)$keyphrase['created']);
				foreach($keyphrase->Option as $option) {
					$k->addOption((string)$option['key'], (string)$option);
				}
				
				$keyphrases[] = $k;
			}
		}
		
		if (isset($xml->Settings->Setting)) {
			foreach($xml->Settings->Setting as $setting) {
				$factory = (string)$setting['factory'];
				$key = (string)$setting['key'];
				if (!isset($factory_settings[$factory])) {
					$factory_settings[$factory] = array();
				}
				$factory_settings[$factory][$key] = (string)$setting;
			}
		}
		
		$this->_setKeyphrases($keyphrases);
		if ($this->_options[self::IMPORT_SETTINGS] && isset($factory_settings['alinks'])) {
			$this->_setSettings($factory_settings['alinks']);
		}
		if ($this->_options[self::IMPORT_FACTORY_SETTINGS]) {
			unset($factory_settings['alinks']);
			$this->_setFactorySettings($factory_settings);
		}
		
		return true;
	}
}